package the.broccoli.uc.controller;

import io.swagger.annotations.ApiParam;
import org.apache.shiro.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.wisteria.framework.web.APIResult;
import org.wisteria.framework.web.BusinessException;
import org.wisteria.framework.web.QueryResult;
import the.broccoli.auth.UserContext;
import the.broccoli.uc.constant.UserTypeEnum;
import the.broccoli.uc.controller.req.UserUpdateReq;
import the.broccoli.uc.entity.User;
import the.broccoli.uc.service.IUserService;
import the.broccoli.uc.vo.UserCondition;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 用户控制器
 * @since 2020-04-11 16:52:59
 */
@RestController
@RequestMapping("/uc/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 新增用户
     */
    @PostMapping("/add")
    public APIResult add(
            @ApiParam(name = "account", value = "账号", required = true)
            @RequestParam(name = "account", required = true) String account,
            @ApiParam(name = "password", value = "密码", required = true)
            @RequestParam(name = "password", required = true) String password,
            @ApiParam(name = "userName", value = "用户名称", required = true)
            @RequestParam(name = "userName", required = true) String userName,
            @ApiParam(name = "phone", value = "手机号码", required = false)
            @RequestParam(name = "phone", required = false) String phone,
            @ApiParam(name = "email", value = "电子邮箱", required = false)
            @RequestParam(name = "email", required = false) String email,
            @ApiParam(name = "userType", value = "账号类型", required = false)
            @RequestParam(name = "userType", required = false) String userType
    ) {
        User entity = new User();
        entity.setDisabled(0);
        entity.setTenantId(UserContext.tenantId());
        entity.setAccount(account);
        entity.setUserName(userName);
        entity.setPhone(phone);
        entity.setEmail(email);
        entity.setUserType(StringUtils.hasText(userType) ? userType : UserTypeEnum.BACKEND.getCode() + "");
        entity.setCreatedId(UserContext.userId());
        entity.setCreatedName(UserContext.userName());
        entity.setCreatedTime(new Date());
        userService.saveAndCheck(entity, password);
        return APIResult.success();
    }

    /**
     * 删除用户
     */
    @PostMapping("/remove")
    public APIResult remove(@RequestParam(value = "ids", required = true) List<String> ids) {
        userService.removeByIds(ids, UserContext.userId(), UserContext.userName());
        return APIResult.success();
    }

    /**
     * 修改用户信息
     */
    @PostMapping("/modify")
    public APIResult modify(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @RequestParam(name = "userId", required = true) String userId,
            @ApiParam(name = "userName", value = "用户名称", required = true)
            @RequestParam(name = "userName", required = true) String userName,
            @ApiParam(name = "phone", value = "手机号码", required = false)
            @RequestParam(name = "phone", required = false) String phone,
            @ApiParam(name = "email", value = "电子邮箱", required = false)
            @RequestParam(name = "email", required = false) String email,
            @ApiParam(name = "userType", value = "账号类型", required = false)
            @RequestParam(name = "userType", required = false) String userType

    ) {
        User entity = new User();
        entity.setUserId(userId);
        entity.setUserName(userName);
        entity.setPhone(phone);
        entity.setEmail(email);
        entity.setUserType(userType);
        entity.setModifiedId(UserContext.userId());
        entity.setModifiedName(UserContext.userName());
        entity.setModifiedTime(new Date());
        userService.updateById(entity);
        return APIResult.success();
    }


    /**
     * 获取用户详情
     * @param userId    用户ID
     */
    @GetMapping("/{userId}")
    public APIResult get(@PathVariable(value = "userId") String userId) {
        return APIResult.success(userService.getById(userId));
    }

    /**
     * 用户查询列表
     */
    @GetMapping("/page")
    public APIResult<QueryResult> page(
            @ApiParam(name = "account", value = "账号", required = false)
            @RequestParam(value = "account", required = false) String account,
            @ApiParam(name = "userName", value = "用户名", required = false)
            @RequestParam(value = "userName", required = false) String userName,
            @ApiParam(name = "orderBy", value = "排序字段", required = false)
            @RequestParam(value = "orderBy", required = false) String orderBy,
            @ApiParam(name = "pageNum", value = "页码", required = false, defaultValue = "1")
            @RequestParam(value = "pageNum", required = false) Integer pageNum,
            @ApiParam(name = "pageNum", value = "每页大小", required = false, defaultValue = "20")
            @RequestParam(value = "pageSize", required = false) Integer pageSize
    ) {
        UserCondition condition = new UserCondition();
        condition.setTenantId(UserContext.tenantId());
        condition.setAccount(account);
        condition.setUserName(userName);
        condition.setUserType(UserTypeEnum.BACKEND.getCode() + "");
        if (!StringUtils.hasText(orderBy)) {
            condition.setOrderBy(" created_time DESC");
        }
        return APIResult.success(userService.pageList(condition, pageNum, pageSize));
    }

    /**
     * 修改登录密码
     */
    @PostMapping("/password")
    public APIResult password(
            @ApiParam(name = "userId", value = "账号", required = true)
            @RequestParam(name = "userId", required = true) String userId,
            @ApiParam(name = "oldPassword", value = "密码", required = true)
            @RequestParam(name = "oldPassword", required = true) String oldPassword,
            @ApiParam(name = "newPassword", value = "新密码", required = true)
            @RequestParam(name = "newPassword", required = true) String newPassword,
            @ApiParam(name = "reNewPassword", value = "确认新密码", required = true)
            @RequestParam(name = "reNewPassword", required = true) String reNewPassword
    ) {
        if (!newPassword.equals(reNewPassword)) {
            throw BusinessException.withMessage("新密码不一致");
        }
        userService.updatePassword(userId, oldPassword, newPassword, UserContext.userId(), UserContext.userName());
        return APIResult.success();
    }

    /**
     * 设置为管理员
     */
    @PostMapping("/setManger")
    public APIResult setManger(
            @ApiParam(name = "account", value = "账号", required = true)
            @RequestParam(name = "account", required = true) String account,
            @ApiParam(name = "userName", value = "用户名", required = false)
            @RequestParam(name = "userName", required = true) String userName,
            @ApiParam(name = "tenantName", value = "租户名", required = false)
            @RequestParam(name = "tenantName", required = true) String tenantName
    ) {
        userService.save(account, userName, tenantName, UserContext.userId(), UserContext.userName());
        return APIResult.success("设置管理员成功");
    }

    /**
     * 禁用/开启账号
     */
    @PostMapping("/setDisabled")
    public APIResult setDisabled(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @RequestParam(name = "userId", required = true) String userId,
            @ApiParam(name = "disabled", value = "0:启用；1:禁用", required = false)
            @RequestParam(name = "disabled", required = false, defaultValue = "1") Integer disabled
    ) {
        User user = new User();
        user.setUserId(userId);
        user.setDisabled(disabled);
        user.setModifiedId(UserContext.userId());
        user.setModifiedTime(new Date());
        userService.updateById(user);
        return APIResult.success();
    }

    /**
     * 更新用户头像
     */
    @PostMapping("/update")
    public APIResult<Boolean> update(@RequestBody @Valid UserUpdateReq req) {
        User user = new User();
        user.setUserId(req.getUserId());
        user.setModifiedTime(new Date());
        user.setUserName(req.getUserName());
        user.setAvatar(req.getAvatar());
        userService.updateById(user);
        return APIResult.success(true);
    }
}